package com.hua.network;

import com.bumptech.glide.util.Executors;
import com.google.gson.GsonBuilder;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitUtil {
    private static final int TIMEOUT = 30;
    private static RetrofitUtil retrofitUtil = null;

    private Retrofit retrofit = null;

    private RetrofitUtil() {

        // 构建OkHttpClient
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(TIMEOUT, TimeUnit.SECONDS) // 连接超时
                .readTimeout(TIMEOUT, TimeUnit.SECONDS) // 读取超时
                .writeTimeout(TIMEOUT, TimeUnit.SECONDS) // 写入超时
                .retryOnConnectionFailure(true) // 连接失败时重试
                .build();

        // 构建Retrofit
        retrofit = new Retrofit.Builder()
                .baseUrl(UrlSect.BASE_URL)
                .client(okHttpClient)
                .callbackExecutor(Executors.mainThreadExecutor())
                .addConverterFactory(GsonConverterFactory.create(
                        new GsonBuilder()
                                .setLenient() // 宽容模式，避免严格的JSON格式检查导致解析失败
                                .create()
                ))
                .build();
    }

    public static RetrofitUtil getInstance() {

        if (retrofitUtil == null) {
            synchronized (RetrofitUtil.class) {
                if (retrofitUtil == null) {
                    return retrofitUtil = new RetrofitUtil();
                }
            }
        }
        return retrofitUtil;
    }

    public<T> T createService(Class<T> serviceClass) {
        return retrofit.create(serviceClass);
    }


    // 清除单例实例（如退出登录时）
    public static void clearInstance() {
        retrofitUtil = null;
    }

}
